import java.util.LinkedList;
import java.util.Queue;

public class LeetCode111 {
    //递归
    public int minDepth(TreeNode node) {
        int res = 0;
        if (node == null) {
            return res;
        }
        int p1 = minDepth(node.left);
        int p2 = minDepth(node.left);
        //当左右子树为null时
        if (p1 == 0 || p2 == 0) {
            //返回左右子树+1
            return p1 + p2 + 1;
        }
        return Integer.min(p1, p2) + 1;
    }

    //层序遍历（广度优先遍历）
    public int minDepth2(TreeNode node) {
        if (node == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(node);
        int depth = 0;
        while (!queue.isEmpty()) {
            depth++;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (poll.left == null && poll.right == null) {
                    return depth;
                }
                if (poll.left != null) {
                    queue.offer(poll.left);
                }
                if (poll.right != null) {
                    queue.offer(poll.right);
                }
            }
        }
        return depth;
    }
}
